/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RCopyDirectoryDialog.java
 *
 * Created on 2011-8-1, 16:27:37
 */
package seso;

import java.awt.Graphics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import org.jdesktop.application.Action;
import org.jdesktop.application.Task;

/**
 *
 * @author Administrator
 */
public class RCopyDirectoryDialog extends javax.swing.JDialog {

    private String directoryFrom = "";
    private String directoryTo = "";
    public boolean dlgResult = true;
    private boolean deleteResult = true;

    /** Creates new form RCopyDirectoryDialog */
    public RCopyDirectoryDialog(java.awt.Frame parent, boolean modal) {
        super(parent, true);
        moreConstruction();
    }

    public RCopyDirectoryDialog(String directoryFrom, String directoryTo) {
        super((java.awt.Frame) null, true);
        this.directoryFrom = directoryFrom;
        this.directoryTo = directoryTo;
        moreConstruction();
    }

    private void moreConstruction() {
        initComponents();

        setSize(borderJPanel.getSize());
        setPreferredSize(getSize());
    }

    public boolean copyDirectory(String file1, String file2) {
        if (!dlgResult) {
            return dlgResult;
        }

        File in = new File(file1);
        File out = new File(file2);

        if (!in.exists()) {
            messageJLabel.setText("Error source directory : " + in.getAbsolutePath());
            dlgResult = false;
            return false;
        } else {
            directoryJLabel.setText(in.getAbsolutePath());
        }

        if (!out.exists()) {
            out.mkdirs();
        }
        if (!out.exists()) {
            messageJLabel.setText("Error !");
            dlgResult = false;
            return false;
        }

        File[] file = in.listFiles();
        FileInputStream fin = null;
        FileOutputStream fout = null;
        for (int i = 0; i < file.length; i++) {

            directoryJProgressBar.setValue((int) ((i + 1) * 1.00 / file.length * 100));

            if (file[i].isFile()) {
                try {
                    fin = new FileInputStream(file[i]);
                } catch (FileNotFoundException e) {
                    messageJLabel.setText("Error !");
                    dlgResult = false;
                    return false;
                }
                fileJLabel.setText(file[i].getName());

                try {
                    fout = new FileOutputStream(new File(file2 + "/" + file[i].getName()));
                } catch (FileNotFoundException e) {
                    messageJLabel.setText("Error !");
                    dlgResult = false;
                    return false;
                }

                int c;
                byte[] b = new byte[1024 * 4];
                //byte[] b = new byte[32];
                fileJProgressBar.setValue(0);
                try {
                    int finAvailable = fin.available();
                    int totalByte = 0;
                    while ((c = fin.read(b)) != -1) {
                        fout.write(b, 0, c);
                        totalByte = totalByte + c;
                        fileJProgressBar.setValue((int) (totalByte * 1.00 / finAvailable * 100));
                        //Thread.sleep(100L);
                    }
                    fin.close();
                    fout.flush();
                    fout.close();
                } catch (Exception e) {
                    messageJLabel.setText("Error !");
                    dlgResult = false;
                    return false;
                }
            } else {
                directoryJLabel.setText(file[i].getName());
                copyDirectory(file1 + "/" + file[i].getName(), file2 + "/" + file[i].getName());
            }
        }

        return dlgResult;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        borderJPanel = new javax.swing.JPanel();
        rDataPanel1 = new seso.RDataPanel();
        jLabel1 = new javax.swing.JLabel();
        directoryJLabel = new javax.swing.JLabel();
        directoryJProgressBar = new javax.swing.JProgressBar();
        messageJLabel = new javax.swing.JLabel();
        fileJProgressBar = new javax.swing.JProgressBar();
        jLabel4 = new javax.swing.JLabel();
        fileJLabel = new javax.swing.JLabel();
        cmdStartButton = new seso.RBgButton();
        cmdCancelButton = new seso.RBgButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);
        setUndecorated(true);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(seso.SesoApp.class).getContext().getResourceMap(RCopyDirectoryDialog.class);
        borderJPanel.setBackground(resourceMap.getColor("borderJPanel.background")); // NOI18N
        borderJPanel.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("borderJPanel.border.lineColor"), 8)); // NOI18N
        borderJPanel.setName("borderJPanel"); // NOI18N
        borderJPanel.setLayout(null);

        rDataPanel1.setName("rDataPanel1"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        rDataPanel1.add(jLabel1);
        jLabel1.setBounds(10, 20, 70, 15);

        directoryJLabel.setText(resourceMap.getString("directoryJLabel.text")); // NOI18N
        directoryJLabel.setName("directoryJLabel"); // NOI18N
        rDataPanel1.add(directoryJLabel);
        directoryJLabel.setBounds(80, 20, 460, 20);

        directoryJProgressBar.setName("directoryJProgressBar"); // NOI18N
        rDataPanel1.add(directoryJProgressBar);
        directoryJProgressBar.setBounds(80, 50, 460, 16);

        messageJLabel.setFont(resourceMap.getFont("messageJLabel.font")); // NOI18N
        messageJLabel.setForeground(resourceMap.getColor("messageJLabel.foreground")); // NOI18N
        messageJLabel.setText(resourceMap.getString("messageJLabel.text")); // NOI18N
        messageJLabel.setName("messageJLabel"); // NOI18N
        rDataPanel1.add(messageJLabel);
        messageJLabel.setBounds(80, 150, 460, 20);

        fileJProgressBar.setName("fileJProgressBar"); // NOI18N
        rDataPanel1.add(fileJProgressBar);
        fileJProgressBar.setBounds(80, 120, 460, 16);

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N
        rDataPanel1.add(jLabel4);
        jLabel4.setBounds(10, 90, 25, 18);

        fileJLabel.setText(resourceMap.getString("fileJLabel.text")); // NOI18N
        fileJLabel.setName("fileJLabel"); // NOI18N
        rDataPanel1.add(fileJLabel);
        fileJLabel.setBounds(80, 90, 460, 15);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(seso.SesoApp.class).getContext().getActionMap(RCopyDirectoryDialog.class, this);
        cmdStartButton.setAction(actionMap.get("cmdStartAction")); // NOI18N
        cmdStartButton.setText(resourceMap.getString("cmdStartButton.text")); // NOI18N
        cmdStartButton.setName("cmdStartButton"); // NOI18N
        rDataPanel1.add(cmdStartButton);
        cmdStartButton.setBounds(160, 190, 100, 30);

        cmdCancelButton.setAction(actionMap.get("cmdCancelAction")); // NOI18N
        cmdCancelButton.setText(resourceMap.getString("cmdCancelButton.text")); // NOI18N
        cmdCancelButton.setName("cmdCancelButton"); // NOI18N
        rDataPanel1.add(cmdCancelButton);
        cmdCancelButton.setBounds(270, 190, 100, 30);

        borderJPanel.add(rDataPanel1);
        rDataPanel1.setBounds(20, 60, 560, 230);

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setForeground(resourceMap.getColor("jLabel2.foreground")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N
        borderJPanel.add(jLabel2);
        jLabel2.setBounds(20, 30, 79, 17);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(borderJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 602, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(borderJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                RCopyDirectoryDialog dialog = new RCopyDirectoryDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public Task cmdStartAction() {
        if (directoryFrom.length() == 0 || directoryTo.length() == 0) {
            dlgResult = false;
            this.dispose();
            return null;
        }
        cmdCancelButton.setVisible(false);

        if (cmdStartButton.getText().trim().equals("Start")) {
            cmdStartButton.setText("Cancel");
            return new cmdStartActionTask(org.jdesktop.application.Application.getInstance(seso.SesoApp.class), cmdStartButton);
        } else if (cmdStartButton.getText().trim().equals("Cancel")) {
            dlgResult = false;
            dispose();
        } else if (cmdStartButton.getText().trim().equals("Continue")) {
            dispose();
        } else if (cmdStartButton.getText().trim().equals("Error")) {
            dlgResult = false;
            dispose();
        }

        return null;
    }

    private class cmdStartActionTask extends org.jdesktop.application.Task<Object, Void> {

        JButton cmdButton;

        cmdStartActionTask(org.jdesktop.application.Application app, JButton cmdButton) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to cmdStartActionTask fields, here.
            super(app);
            this.cmdButton = cmdButton;
        }

        @Override
        protected Object doInBackground() {
            // Your Task's code here.  This method runs
            // on a background thread, so don't reference
            // the Swing GUI from here.
            if (deleteDirectory(directoryTo)) {
                copyDirectory(directoryFrom, directoryTo);
                if (dlgResult) {
                    cmdButton.setText("Continue");
                } else {
                    cmdButton.setText("Error");
                }
            } else {
                cmdButton.setText("Error");
            }
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    public boolean deleteDirectory(String paraDirectory) {

        if (!deleteResult) {
            return deleteResult;
        }

        File inDirectory = new File(paraDirectory);

        if (!inDirectory.exists()) {
            deleteResult = true;
            return deleteResult;
        }

        File[] file = inDirectory.listFiles();

        if (file.length == 0) {
            try {
                inDirectory.delete();
            } catch (Exception e) {
                deleteResult = false;
                return deleteResult;
            }
        } else {
            for (int i = 0; i < file.length; i++) {

                if (file[i].isFile()) {
                    try {
                        file[i].delete();
                    } catch (Exception e) {
                        deleteResult = false;
                        return deleteResult;
                    }
                } else {
                    deleteDirectory(paraDirectory + "/" + file[i].getName());
                }
            }

            try {
                inDirectory.delete();
            } catch (Exception e) {
                deleteResult = false;
                return deleteResult;
            }
        }

        return deleteResult;
    }

    @Action
    public Task cmdCancelAction() {

        dlgResult = false;
        this.dispose();
        return null;
        //return new CmdCancelActionTask(org.jdesktop.application.Application.getInstance(seso.SesoApp.class));
    }

    /*
    private class CmdCancelActionTask extends org.jdesktop.application.Task<Object, Void> {

        CmdCancelActionTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to CmdCancelActionTask fields, here.
            super(app);
        }

        @Override
        protected Object doInBackground() {
            // Your Task's code here.  This method runs
            // on a background thread, so don't reference
            // the Swing GUI from here.
            return null;  // return your result
        }

        @Override
        protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }
     * 
     */
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel borderJPanel;
    private seso.RBgButton cmdCancelButton;
    private seso.RBgButton cmdStartButton;
    private javax.swing.JLabel directoryJLabel;
    private javax.swing.JProgressBar directoryJProgressBar;
    private javax.swing.JLabel fileJLabel;
    private javax.swing.JProgressBar fileJProgressBar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel messageJLabel;
    private seso.RDataPanel rDataPanel1;
    // End of variables declaration//GEN-END:variables
}
